#!/bin/bash

export WORKDIR=${PROJECT_PATH_FIX}

#检查工具是否存在,$1为待检查的工具名。
function CheckTool
{
	[  -n "$1"  ] ||
	{
		echo -e  "\033[41;37mCheckTool 参数错误!!\r\n\033[40;37m";
		return 255;
	};
	ToolPath=`which $1`;
	[ -e "$ToolPath" ] ||
	{
		 echo -e "\033[41;37m$1 不存在，请先安装此工具\r\n\033[40;37m";
		 return 255;
	};
	return 0;
}

#检查必要的工具
CheckTool git
[ $? -eq 0 ] || exit;
CheckTool patch
[ $? -eq 0 ] || exit;
CheckTool ls
[ $? -eq 0 ] || exit;
CheckTool cmd
[ $? -eq 0 ] || exit;
CheckTool python
[ $? -eq 0 ] || exit;
CheckTool pkgs
[ $? -eq 0 ] || exit;
CheckTool scons
[ $? -eq 0 ] || exit;

#更新python软件包
python -m pip install -U pip || python  ${WORKDIR}/tools/bin/get-pip.py
python -m pip install -U scons

echo -e  "\033[44;37m工程目录:${PROJECT_PATH_FIX}\r\n\033[40;37m";

echo -e   "\033[44;37m下载第三方源代码\r\n\033[40;37m";

cd ${WORKDIR}
git clean -x -f -d
git submodule update --init --force --recursive
[ $? -eq 0 ] || exit;
cd ${RTTHREADDIR}
#恢复rt-thread源代码目录
git clean -f
[ $? -eq 0 ] || exit;
git reset --hard
[ $? -eq 0 ] || exit;
cd ${WORKDIR}


echo -e   "\033[44;37m处理相关文件\r\n\033[40;37m";

rm -rf ${RTTHREADBSPDIR}/applications
rm -rf ${RTTHREADBSPDIR}/.config
cp -f ${WORKDIR}/.config ${RTTHREADBSPDIR}/.config
cp -f ${WORKDIR}/rtconfig.h ${RTTHREADBSPDIR}/rtconfig.h
cmd /c mklink.bat
if [ -f ${WORKDIR}/Kconfig ]; then echo 'source "$RTT_DIR/../Kconfig"' >> ${RTTHREADBSPDIR}/Kconfig; fi

echo -e   "\033[44;37m处理相关补丁\r\n\033[40;37m";
cd ${WORKDIR}

#减少git换行符问题
git checkout patches
[ $? -eq 0 ] || exit;

for i in `ls "patches/*.patch" 2>/dev/null`
do
echo applying $i
patch  -p1 --binary  -d ${RTTHREADDIR} < ${WORKDIR}/$i;
[ $? -eq 0 ] || exit;
echo -e "\r\n";
done

echo -e   "\033[44;37m生成Keil5工程文件\r\n\033[40;37m";
cd  ${RTTHREADBSPDIR}
cmd /c  pkgs --update
[ $? -eq 0 ] || exit;
cmd /c scons --target=mdk5
[ $? -eq 0 ] || exit;
cd ${WORKDIR}

echo -e   "\033[44;37m处理已完成!请打开project.uvprojx进行编译调试\r\n\033[40;37m";
